package com.wosiliujing.learning.handler;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Optional;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR;

/**
 * @author liujing
 */
@Slf4j
@Component
@AllArgsConstructor
public class HystrixHandler implements HandlerFunction<ServerResponse> {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest)  {
        Optional<Object> originalUrls = serverRequest.attribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        log.error("网关请求失败，服务降级处理:{}",originalUrls);
        try {
            return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(BodyInserters.fromObject(objectMapper.writeValueAsString(new Result(500,"网络繁忙"))));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Data
    @JsonInclude(value=JsonInclude.Include.NON_NULL)
    @AllArgsConstructor
    static class Result{
        private int code;
        private String msg;
    }
}
